package com.lanju.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.lanju.common.SpringUtils;
import com.lanju.entity.Certificate;
import com.lanju.entity.User;
import com.lanju.service.CertificateService;

@Controller
@RequestMapping("certificate")
public class CertificateController {
	
	private static final Logger LOGGER = LoggerFactory
            .getLogger(CertificateController.class);
	@Autowired
	CertificateService certificateService;
	
	/**
	 * 上传证件
	 * 作者：zengqd
	 * @param request
	 * @param session
	 * @param otherCerti
	 * @param bankCard
	 * @param houseCard
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("uploadCertificate")
	@ResponseBody
	public Map<String,Object> uploadCertificate(HttpServletRequest request,HttpSession session,
			@RequestParam(value = "otherCerti", required = false) MultipartFile[] otherCerti,
			@RequestParam(value = "bankCard", required = false) MultipartFile bankCard,
			@RequestParam(value = "houseCard", required = false) MultipartFile houseCard,
			@RequestParam(value = "otherCerti1", required = false) MultipartFile[] otherCerti1,
			@RequestParam(value = "bankCard1", required = false) MultipartFile bankCard1,
			@RequestParam(value = "houseCard1", required = false) MultipartFile houseCard1,
			@RequestParam(value ="houseId", required = false) String houseId,
			@RequestParam(value ="userId", required = false) String userId,
			@RequestParam(value="delArr" ,required =false) String delArr){
		Map<String, Object> param = SpringUtils.getParameterMap(request);
		Map<String,Object> result=new HashMap<String, Object>();
		try {
			User user =(User) session.getAttribute("userModel");
			param.put("creator", user.getUserId());
			if(otherCerti != null ){
				List<String> list=ImageOptController.mutiPicUpload(otherCerti);
				if(list !=null && list.size()>0){
					JSONArray arr=	JSONArray.parseArray(delArr);
					if(arr !=null && arr.size()>0){
						String urls="";
						for(int i=0;i<arr.size();i++){
							urls="'"+arr.get(i)+"',";
						}
						System.out.println("urls=="+urls);
						param.put("url",urls.substring(0, urls.length()-1));
						param.put("type", "othercard");
						certificateService.delCertificate(param);
					}
					for(int i=0;i<list.size();i++){
						param.put("url",list.get(i));
						param.put("type", "othercard");
						certificateService.saveCertificate(param);
					}
					
				}
				
			}
			if(otherCerti1 != null ){
				List<String> list=ImageOptController.mutiPicUpload(otherCerti1);
				if(list !=null && list.size()>0){
					JSONArray arr=	JSONArray.parseArray(delArr);
					if(arr !=null && arr.size()>0){
						String urls="";
						for(int i=0;i<arr.size();i++){
							urls+="'"+arr.get(i)+"',";
						}
						System.out.println("urls=="+urls);
						param.put("url",urls.substring(0, urls.length()-1));
						param.put("type", "othercard");
						certificateService.delCertificate(param);
					}
					for(int i=0;i<list.size();i++){
						param.put("url",list.get(i));
						param.put("type", "othercard");
						Certificate c=	certificateService.getCertificate(param);
						if(c != null){
							param.put("certificate_id", c.getCertificate_id());
							certificateService.delCertificate(param);
							certificateService.saveCertificate(param);
						}else{
							certificateService.saveCertificate(param);
						}
						
					}
				}
				
			}
			if(bankCard !=null){
				String baneurl=ImageOptController.onePicUpload(bankCard);
				param.put("url", baneurl);
				param.put("type", "bankcard");
				Certificate c=	certificateService.getCertificate(param);
				if(c !=null){
					param.put("certificate_id", c.getCertificate_id());
					certificateService.updateCertificate(param);
				}else{
					certificateService.saveCertificate(param);
				}
			}
			if(bankCard1 !=null){
				String baneurl=ImageOptController.onePicUpload(bankCard1);
				param.put("url", baneurl);
				param.put("type", "bankcard");
				Certificate c=	certificateService.getCertificate(param);
				if(c !=null){
					param.put("certificate_id", c.getCertificate_id());
					certificateService.updateCertificate(param);
				}else{
					certificateService.saveCertificate(param);
				}
			}
			if(houseCard !=null){
				String houseurl=ImageOptController.onePicUpload(houseCard);
				param.put("url", houseurl);
				param.put("type", "housecard");
				Certificate c=	certificateService.getCertificate(param);
				if(c !=null){
					param.put("certificate_id", c.getCertificate_id());
					certificateService.updateCertificate(param);
				}else{
					certificateService.saveCertificate(param);
				}
			}
			if(houseCard1 !=null){
				String houseurl=ImageOptController.onePicUpload(houseCard1);
				param.put("url", houseurl);
				param.put("type", "housecard");
				Certificate c=	certificateService.getCertificate(param);
				if(c !=null){
					param.put("certificate_id", c.getCertificate_id());
					certificateService.updateCertificate(param);
				}else{
					certificateService.saveCertificate(param);
				}
			}
			result.put("success", true);
			result.put("msg", "上传成功");
			LOGGER.info("上传成功");
		} catch (Exception e) {
			e.printStackTrace();
			result.put("success", false);
			result.put("msg", "上传失败");
			LOGGER.info("上传失败");
		}
		return result;
	}
	/**
	 * 查询某一个房子的证件
	 * 作者：zengqd
	 * @param request
	 * @return
	 */
	@RequestMapping("getAllCertificateList")
	@ResponseBody
	public Map<String,Object> getAllCertificateList(HttpServletRequest request){
		Map<String, Object> param = SpringUtils.getParameterMap(request);
		return certificateService.getAllCertificateList(param);
	}
	/**
	 * 获取用户身份证信息
	 * 作者：zengqd
	 * @param request
	 * @return
	 */
	@RequestMapping("getUserIdCardInfo")
	@ResponseBody
	public Map<String,Object> getUserIdCardInfo(HttpServletRequest request){
		Map<String, Object> param = SpringUtils.getParameterMap(request);
		return certificateService.getUserIdCardInfo(param);
	}
	/**
	 * 添加身份证
	 * 作者：zengqd
	 * @param zhengmian
	 * @param fanmian
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/addIdCard")
	@ResponseBody
	public Map<String,Object> addIdCard(@RequestParam(value="zhengmian",required=false) MultipartFile[] zhengmian,
	    		@RequestParam(value="fanmian",required=false) MultipartFile[] fanmian,HttpServletRequest request,HttpSession session,
	    		@RequestParam(value="delArr" ,required =false) String delArr){
	    	Map<String, Object> param = SpringUtils.getParameterMap(request);
	    	User user =(User) session.getAttribute("userModel");
	    	String contentType = request.getContentType();
	        if (contentType == null || !contentType.toLowerCase().startsWith("multipart/")) {
	            throw new MultipartException("The current request is not a multipart request");
	        }
	    	try {
	    		param.put("delArr", delArr);
	    		param.put("userId", user.getUserId());
	    		if(zhengmian.length>0){
	    			String zhengmianurl=uploadImg(zhengmian);
	    			param.put("zhengmianurl", zhengmianurl);
	    		}
	        	if(fanmian.length>0){
	        		String fanmianurl=uploadImg(fanmian);
	        		param.put("fanmianurl", fanmianurl);
	        	}
	        	return certificateService.addIdCard(param);
	        	
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
			
	    }
	 
	 private String uploadImg(MultipartFile[] files) {
			String Url = null;
			if (files != null && files.length > 0) {
				// 循环获取file数组中得文件
				for (int i = 0; i < files.length; i++) {
			MultipartFile file = files[i];
			 OutputStream os = null;
			 InputStream in= null;
			 String picPath=null;
	        try {
	        	in=file.getInputStream();
	   		 // 2、保存到临时文件
	           // 1K的数据缓冲
	           byte[] bs = new byte[1024];
	           // 读取到的数据长度
	           int len;
	           // 输出的文件流保存到本地文件
	           File tempFile = new File("/webapp/lanjufile/idcard/");//linux
//	             File tempFile = new File("D:/upFiles/idcard/");
	           if (!tempFile.exists()) {
	               tempFile.mkdirs();
	           }else{
	           	LOGGER.info("文件已存在");
	           }
//	           String fullPath="D:/upFiles/idcard/"+file.getOriginalFilename();
	           String fullPath="/webapp/lanjufile/idcard/"+file.getOriginalFilename();//linux
	           System.out.println("文件全路径"+fullPath);
				os = new FileOutputStream(fullPath);
				while ((len = in.read(bs)) != -1) {
				    try {
						os.write(bs, 0, len);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				os.close();
				in.close();
			} catch (Exception e3) {
				e3.printStackTrace();
			}
	       Url = "/dataResourceImages/idcard/"+file.getOriginalFilename();
	      
		}  
			}
			 return Url;
		}

}
